package com.thinksns.sociax.t4.android.verify;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.thinksns.sociax.android.R;
import com.thinksns.sociax.api.ApiVerify;
import com.thinksns.sociax.component.CustomTitle;
import com.thinksns.sociax.component.LeftAndRightTitle;
import com.thinksns.sociax.t4.adapter.AdapterViewPager;
import com.thinksns.sociax.t4.android.ThinksnsAbscractActivity;
import com.thinksns.sociax.t4.android.video.ToastUtils;
import com.thinksns.sociax.t4.component.SmallDialog;
import com.thinksns.sociax.t4.model.VerifyDetails;
import com.thinksns.sociax.t4.model.VerifyModel;
import com.thinksns.sociax.t4.unit.UnitSociax;
import com.thinksns.sociax.thinksnsbase.activity.widget.EmptyLayout;
import com.thinksns.sociax.thinksnsbase.network.ApiHttpClient;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.CommonPagerTitleView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;

/**
 * @author LeiYan
 * @describe 认证填写信息页 and 编辑页
 * @date 2017/7/20
 * @contact email:907238552@qq.com
 */

public class DoVerifyHomeActivity extends ThinksnsAbscractActivity {

    @BindView(R.id.indicator_container)
    MagicIndicator mMagicIndicator;

    @BindView(R.id.vp_verify)
    ViewPager mViewPager;

    @BindView(R.id.empty_layout)
    EmptyLayout mEmptyLayout;

    private CommonNavigator mCommonNavigator;
    private List<String> mIndicatorList;
    private VerifyOtherPopupWindow mVerifyOtherPopupWindow;
    private List<Fragment> mFragmentsList;
    private Fragment mCurrentFragment;
    private VerifyDetails mUserVerifyDetails;
    private int mDefaultSelectPos = 0; // viewPager 默认选中位置

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init();
        getUserVerifyList();

    }

    private void init() {
        mUserVerifyDetails = (VerifyDetails) getIntent().getSerializableExtra("detail"); // 用户重新提交传入过往认证信息
        mIndicatorList = new ArrayList<>();
        mIndicatorList.add(getString(R.string.type_verify_personal));
        mIndicatorList.add(getString(R.string.type_verify_organization));
        mEmptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
        mEmptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mEmptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
                getUserVerifyList();
            }
        });
    }

    @Override
    public String getTitleCenter() {
        return getString(R.string.title_verify_home_verify);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_do_verify_home;
    }

    @Override
    protected CustomTitle setCustomTitle() {
        return new LeftAndRightTitle(R.drawable.img_back, this);
    }

    private void initPagerAdapter(List<VerifyModel> verifyModels) {
        AdapterViewPager adapterViewPager = new AdapterViewPager(getSupportFragmentManager());
        mFragmentsList = getFragments(verifyModels);
        adapterViewPager.bindData(mFragmentsList);
        mViewPager.setAdapter(adapterViewPager);
        mViewPager.setOffscreenPageLimit(mFragmentsList.size());
    }

    public List<Fragment> getFragments(List<VerifyModel> verifyModels) {
        /*if mUserVerifyDetails is not null, calculate the pos which selected by viewPager */
        if (mUserVerifyDetails != null) {
            for (int i = 0; i < verifyModels.size(); i++) {
                if (mUserVerifyDetails.getUsergroup_id() == Integer.parseInt(verifyModels.get(i).getVerify_id())) {
                    mDefaultSelectPos = i;
                    break;
                }
            }
            mDefaultSelectPos = mDefaultSelectPos > 2 ? 2 : mDefaultSelectPos;
        }
        List<Fragment> list = new ArrayList();
        // 个人
        list.add(VerifyFragment.newInstance(mUserVerifyDetails, verifyModels.get(0)));
        // 机构
        list.add(VerifyFragment.newInstance(mUserVerifyDetails, verifyModels.get(1)));
        // 其他
        List<VerifyModel> other = (List<VerifyModel>) ((ArrayList) verifyModels).clone();
        other.remove(0);
        other.remove(0);
        if (other.isEmpty()) {
            return list;
        }
        /*if has other type, */
        mIndicatorList.add(getString(R.string.type_verify_other));
        mVerifyOtherPopupWindow = new VerifyOtherPopupWindow(this, other);

        VerifyModel otherSelect = null;
        if (mUserVerifyDetails != null && mDefaultSelectPos == 2) {
            for (int i = 0; i < other.size(); i++) {
                if (mUserVerifyDetails.getUsergroup_id() == Integer.parseInt(other.get(i).getVerify_id())) {
                    otherSelect = other.get(i);
                    mVerifyOtherPopupWindow.setSelectPos(i);
                    mIndicatorList.set(2, otherSelect.getTitle());
                    break;
                }
            }
        }
        list.add(VerifyFragment.newInstance(mUserVerifyDetails, otherSelect));

        return list;
    }

    /**
     * init indicator
     */
    private void initNavigator() {
        final int width = UnitSociax.getWindowWidth(this) / mIndicatorList.size();
        mCommonNavigator = new CommonNavigator(this);
        mCommonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return mIndicatorList.size();
            }

            @Override
            public IPagerTitleView getTitleView(final Context context, final int i) {
                View view = LayoutInflater.from(context).inflate(R.layout.view_indicator_verify, null, false);
                view.setMinimumWidth(width);
                final TextView textView = (TextView) view.findViewById(R.id.tv_indicator);
                final ImageView imageView = (ImageView) view.findViewById(R.id.iv_indicator);
                final CommonPagerTitleView titleView = new CommonPagerTitleView(context);
                titleView.setContentView(view);
                imageView.setVisibility(View.GONE);
                if (i == 2 && !mVerifyOtherPopupWindow.isSelect()) {
                    imageView.setVisibility(View.VISIBLE);
                }
                textView.setText(mIndicatorList.get(i));
                if (mVerifyOtherPopupWindow != null) {
                    mVerifyOtherPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            VerifyModel model = (VerifyModel) view.getTag();
                            textView.setText(model.getTitle());
                            imageView.setVisibility(View.GONE);
                            ((VerifyFragment) mFragmentsList.get(2)).refreshUserVerifyType(model, mUserVerifyDetails);
                        }
                    });
                }
                titleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(final View v) {
                        mViewPager.setCurrentItem(i);
                        mCurrentFragment = mFragmentsList.get(i);
                        if (i == 2) {
                            mVerifyOtherPopupWindow.showAsDrop(mMagicIndicator);
                        }
                    }
                });
                titleView.setOnPagerTitleChangeListener(new CommonPagerTitleView.OnPagerTitleChangeListener() {
                    @Override
                    public void onSelected(int i, int i1) {
                        textView.setTextColor(ContextCompat.getColor(context, R.color.tab_selected_text_color));
                        mCurrentFragment = mFragmentsList.get(i);
                    }

                    @Override
                    public void onDeselected(int i, int i1) {
                        textView.setTextColor(ContextCompat.getColor(context, R.color.tab_text_color));
                    }

                    @Override
                    public void onLeave(int i, int i1, float v, boolean b) {

                    }

                    @Override
                    public void onEnter(int i, int i1, float v, boolean b) {
                        if (i == 2 && mVerifyOtherPopupWindow != null && !mVerifyOtherPopupWindow.isSelect()) {
                            Log.v("tagLei", "onEnter...");
                            mVerifyOtherPopupWindow.showAsDrop(mMagicIndicator);
                        }
                    }
                });
                return titleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                indicator.setColors(ContextCompat.getColor(context, R.color.tab_indicator_color));
                return indicator;
            }
        });
        mMagicIndicator.setNavigator(mCommonNavigator);
        ViewPagerHelper.bind(mMagicIndicator, mViewPager);
        mViewPager.setCurrentItem(mDefaultSelectPos);
        mCurrentFragment = mFragmentsList.get(mDefaultSelectPos);
    }

    private void getUserVerifyList() {
        ApiVerify.getInstance().getUserVerify(new ApiHttpClient.HttpResponseListener() {
            @Override
            public void onSuccess(Object result) {
                List<VerifyModel> verifyModels = (List<VerifyModel>) result;
                initPagerAdapter(verifyModels);
                initNavigator();
                mEmptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
            }

            @Override
            public void onError(Object result) {
                mEmptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
                ToastUtils.showToast(result == null ? getString(R.string.net_fail) : String.valueOf(result));
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (mCurrentFragment != null) {
            mCurrentFragment.onActivityResult(requestCode, resultCode, data);
        }
    }
}
